package net.cnki.sunny.exception;

import cn.hutool.core.exceptions.ValidateException;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.cnki.sunny.common.ResultVO;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class GlobalExceptionResolver implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        if (e instanceof ValidateException) {
            try {
                httpServletResponse.setContentType("application/json;charset=UTF-8");
                httpServletResponse.getWriter().write(new ObjectMapper().writeValueAsString(new ResultVO<>().error(e.getMessage())));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }else{
            e.printStackTrace();
        }
        return new ModelAndView();
    }
}
